<template>
  <div class="recommended-routes-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">
        <el-icon><Trophy /></el-icon>
        热门路线推荐
      </h1>
      <p class="page-subtitle">发现其他用户分享的优质旅游路线</p>
    </div>

    <!-- 筛选栏 -->
    <el-card class="filter-card" shadow="hover">
      <el-row :gutter="20" align="middle">
        <el-col :span="8">
          <el-select
            v-model="filterType"
            placeholder="排序方式"
            style="width: 100%"
            @change="fetchRoutes"
          >
            <el-option label="最新发布" value="latest" />
            <el-option label="最受欢迎" value="popular" />
            <el-option label="费用最低" value="cost_low" />
            <el-option label="距离最短" value="distance_short" />
          </el-select>
        </el-col>
        <el-col :span="8">
          <el-input-number
            v-model="limit"
            :min="5"
            :max="50"
            :step="5"
            label="显示数量"
            style="width: 100%"
            @change="fetchRoutes"
          />
        </el-col>
        <el-col :span="8" style="text-align: right;">
          <el-button :icon="RefreshRight" @click="fetchRoutes">刷新</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 路线列表 -->
    <div v-loading="loading" class="routes-grid">
      <el-card
        v-for="route in routes"
        :key="route.id"
        class="route-card"
        shadow="hover"
        @click="viewRoute(route)"
      >
        <template #header>
          <div class="card-header">
            <h3 class="route-title">
              <el-icon><MapLocation /></el-icon>
              {{ route.start_attraction?.name || '路线规划' }}
            </h3>
            <el-tag type="success" v-if="route.is_shared">已分享</el-tag>
          </div>
        </template>

        <div class="route-summary">
          <el-descriptions :column="2" size="small" border>
            <el-descriptions-item label="起始景点">
              {{ route.start_attraction?.name || '未知' }}
            </el-descriptions-item>
            <el-descriptions-item label="景点数量">
              {{ route.optimal_route?.route?.length || 0 }} 个
            </el-descriptions-item>
            <el-descriptions-item label="预算">
              ¥{{ route.budget }}
            </el-descriptions-item>
            <el-descriptions-item label="总费用">
              <span class="cost-text">¥{{ route.total_cost }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="总距离">
              {{ route.total_distance }} 公里
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(route.created_at) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 路线预览 -->
        <div v-if="route.optimal_route?.details" class="route-preview">
          <el-timeline>
            <el-timeline-item
              v-for="(detail, index) in route.optimal_route.details.slice(0, 3)"
              :key="index"
              :timestamp="`第${detail.order}站`"
              placement="top"
              size="small"
            >
              <div class="timeline-content">
                <strong>{{ detail.attraction_name }}</strong>
                <span class="preview-price">¥{{ detail.ticket_price }}</span>
              </div>
            </el-timeline-item>
            <el-timeline-item
              v-if="route.optimal_route.details.length > 3"
              timestamp="..."
              placement="top"
              size="small"
            >
              <div class="timeline-content">
                还有 {{ route.optimal_route.details.length - 3 }} 个景点
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>

        <div class="card-footer">
          <el-button type="primary" @click.stop="viewRoute(route)">
            查看详情
          </el-button>
          <el-button
            v-if="route.share_code"
            type="success"
            :icon="Share"
            @click.stop="copyShareLink(route.share_code)"
          >
            复制链接
          </el-button>
        </div>
      </el-card>

      <!-- 空状态 -->
      <el-empty
        v-if="!loading && routes.length === 0"
        description="暂无推荐路线"
        :image-size="150"
      />
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Trophy, MapLocation, RefreshRight, Share } from '@element-plus/icons-vue'
import TravelAPI from '../api/travel'
import logger from '../utils/logger'

export default {
  name: 'RecommendedRoutes',
  components: {
    Trophy,
    MapLocation
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const routes = ref([])
    const filterType = ref('latest')
    const limit = ref(10)

    // 获取推荐路线
    const fetchRoutes = async () => {
      loading.value = true
      try {
        const response = await TravelAPI.getRecommendedRoutes({
          limit: limit.value
        })
        routes.value = response.results || []
      } catch (error) {
        logger.error('获取推荐路线失败:', error)
        ElMessage.error('获取推荐路线失败')
      } finally {
        loading.value = false
      }
    }

    // 查看路线详情
    const viewRoute = (route) => {
      if (route.share_code) {
        router.push(`/route-share/${route.share_code}`)
      } else {
        ElMessage.warning('该路线未分享')
      }
    }

    // 复制分享链接
    const copyShareLink = async (shareCode) => {
      const shareUrl = `${window.location.origin}/route-share/${shareCode}`
      try {
        await navigator.clipboard.writeText(shareUrl)
        ElMessage.success('链接已复制到剪贴板')
      } catch (error) {
        // 降级方案
        const textArea = document.createElement('textarea')
        textArea.value = shareUrl
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        ElMessage.success('链接已复制到剪贴板')
      }
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return ''
      const d = new Date(date)
      return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
    }

    onMounted(() => {
      fetchRoutes()
    })

    return {
      loading,
      routes,
      filterType,
      limit,
      fetchRoutes,
      viewRoute,
      copyShareLink,
      formatDate,
      RefreshRight,
      Share
    }
  }
}
</script>

<style scoped>
.recommended-routes-page {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
  /* 南昌旅游特色：天空蓝渐变背景 */
  background: linear-gradient(135deg, #E3F2FD 0%, #BBDEFB 50%, #90CAF9 100%);
  min-height: 100vh;
  animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  margin-bottom: 20px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  /* 南昌红主题色 */
  color: #C8102E;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.page-subtitle {
  color: #909399;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
  box-shadow: 0 2px 12px rgba(200, 16, 46, 0.08);
  transition: all 0.3s ease;
}

.filter-card:hover {
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.16);
  transform: translateY(-2px);
  border-color: rgba(212, 175, 55, 0.3);
}

.routes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.route-card {
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(200, 16, 46, 0.1);
  background: linear-gradient(135deg, rgba(255,255,255,0.95) 0%, rgba(227,242,253,0.8) 100%);
  backdrop-filter: blur(10px);
}

.route-card:hover {
  transform: translateY(-8px) scale(1.02);
  box-shadow: 0 8px 24px rgba(200, 16, 46, 0.2);
  border-color: rgba(212, 175, 55, 0.3);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.route-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 8px;
}

.route-summary {
  margin: 15px 0;
}

.cost-text {
  /* 滕王阁金色 */
  color: #D4AF37;
  font-weight: 600;
  font-size: 16px;
}

.route-preview {
  margin: 15px 0;
  padding: 15px;
  background: linear-gradient(135deg, rgba(227,242,253,0.5) 0%, rgba(255,255,255,0.8) 100%);
  border-radius: 8px;
  border: 1px solid rgba(200, 16, 46, 0.1);
}

.timeline-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.preview-price {
  color: #909399;
  font-size: 12px;
}

.card-footer {
  display: flex;
  gap: 10px;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .routes-grid {
    grid-template-columns: 1fr;
  }
}
</style>

